package org.springblade.common.handle;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springblade.modules.admin.entity.UserWeixin;
import org.springblade.modules.admin.service.UserWeixinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
public class SubscribeHandler implements WxMpMessageHandler {

	@Autowired
	private UserWeixinService userWeixinService;

	@Override
	public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
									Map<String, Object> context, WxMpService weixinService,
									WxSessionManager sessionManager) throws WxErrorException {

		log.info("关注用户 OPENID: " + wxMessage.getFromUser());

		// 获取微信用户基本信息
		try {
			WxMpUser userWxInfo = weixinService.getUserService().userInfo(wxMessage.getFromUser(), null);
			if (userWxInfo != null) {
				// 更新数据库状态为关注状态
				userWeixinService.update(Wrappers.<UserWeixin>lambdaUpdate().set(UserWeixin::getSubscribe,1).eq(UserWeixin::getOpenid,userWxInfo.getOpenId()));
			}
		} catch (WxErrorException e) {
			if (e.getError().getErrorCode() == 48001) {
				log.info("该公众号没有获取用户信息权限！");
			}
		}

		WxMpXmlOutMessage responseResult = null;
		try {
			responseResult = this.handleSpecial(wxMessage);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

		if (responseResult != null) {
			return responseResult;
		}

		try {
			WxMpXmlOutTextMessage message = WxMpXmlOutMessage.TEXT().content("感谢关注")
				.fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
				.build();
			return message;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

		return null;
	}

	/**
	 * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
	 */
	private WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage)
		throws Exception {
		//TODO
		return null;
	}

}
